package com.filldream.fastboot.common.okutil.stock.cls.zdStatistics;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.filldream.fastboot.common.okutil.stock.cf.CfKLineUtil;
import com.filldream.fastboot.common.okutil.stock.cf.kline.GetKLineSTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineDTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineItemDTO;
import com.filldream.fastboot.common.okutil.stockIndex.StockIndexUtil;
import com.filldream.fastboot.common.stockUtils.cf.CfUtil;
import com.filldream.fastboot.common.stockUtils.qt.entity.StockInfo;
import com.filldream.fastboot.common.stockUtils.qt.StockUtil;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ClsZdStatisticsUtil {

    /**
     * 获取同花顺涨跌分布统计-组合
     * @return
     */
    public static JSONObject getClsZdData(){
        JSONObject result;
        result = getEmotion();
        JSONObject zdStatistics2 = getZdStatistics();
        if( zdStatistics2 != null && zdStatistics2.containsKey("code") && zdStatistics2.getIntValue("code") == 200 ){
            JSONObject data = result.getJSONObject("data");
            data.put("up_down_dis", zdStatistics2.getJSONObject("data").getJSONObject("up_down_dis"));
        }
        //查询股价
        List<StockInfo> stockInfos = StockUtil.getByCodes("sh000001,sz399001,sz399006,sh204001");
        //两市市值
        stockInfos.add(dealMarkPrice(stockInfos));
        //东方财富查询
        List<StockInfo> cfStock = CfUtil.getStockList("100.HSI,124.HSTECH,251.HXC,104.CN00Y,47.800005,133.USDCNH,100.UDI,122.XAU,112.B00Y,171.US10Y,171.CN30Y,134.HTI_M");
        stockInfos.addAll( cfStock );
        JSONObject data = result.getJSONObject("data");
        data.put("stock_list", deal(stockInfos));
        return result;
    }

    private static List<StockInfo> deal(List<StockInfo> stockInfos) {
        List<StockInfo> list = new ArrayList<>();
        stockInfos.forEach( item -> {
            StockInfo stockInfo = new StockInfo();
            stockInfo.setName(item.getName());
            stockInfo.setSearchCode(item.getSearchCode());
            stockInfo.setNowPrice(item.getNowPrice());
            stockInfo.setZde(item.getZde());
            stockInfo.setZf(item.getZf());
            list.add(stockInfo);
        });
        return list;
    }

    /**
     * 处理港股指数的延迟问题
     * @param code
     * @return
     */
    public static StockInfo dealHk(String code){
        //优化恒生科技的
        GetKLineSTO getKLineSTO = new GetKLineSTO();
        getKLineSTO.setSearchCode(code);
        getKLineSTO.setType(3);
        KLineDTO kLine = CfKLineUtil.getKLine(getKLineSTO);
        KLineItemDTO kLineItemDTO = kLine.getList().get(kLine.getList().size() - 1);
        StockInfo stockInfo = new StockInfo();
        stockInfo.setName(code.equals("hkHSTECH") ? "恒生科技" : ( code.equals("47.800005") ? "平均股价" : "恒生指数") );
        stockInfo.setNowPrice(kLineItemDTO.getClose());
        stockInfo.setZde(kLineItemDTO.getZde());
        stockInfo.setZf(kLineItemDTO.getZdf());
        return stockInfo;
    }

    public static StockInfo dealA50(){
        JSONObject a50KeepDate = StockIndexUtil.getA50KeepDate();
        BigDecimal a50Price = a50KeepDate.getBigDecimal("f43").divide(new BigDecimal("10"),1,BigDecimal.ROUND_DOWN);
        BigDecimal a50Zdf = a50KeepDate.getBigDecimal("f170").divide(new BigDecimal("100"),2,BigDecimal.ROUND_DOWN);
        BigDecimal a50Zde = a50KeepDate.getBigDecimal("f169").divide(new BigDecimal("10"),2,BigDecimal.ROUND_DOWN);
        StockInfo stockInfo = new StockInfo();
        stockInfo.setName("富时A50");
        stockInfo.setNowPrice(a50Price);
        stockInfo.setZde(a50Zde);
        stockInfo.setZf(a50Zdf);
        return stockInfo;
    }

    public static StockInfo dealHl(String code){
        JSONObject usdcnh = StockIndexUtil.getDiyHL(code);
        String price = usdcnh.getString("price");
        String increase = usdcnh.getString("increase");
        String ratio = usdcnh.getString("ratio").replace("%","");
        //保留两位小数的价格
        BigDecimal priceMoney = new BigDecimal(price).setScale(3, BigDecimal.ROUND_DOWN);
        BigDecimal increaseMoney = new BigDecimal(increase).setScale(3, BigDecimal.ROUND_DOWN);
        BigDecimal ratioMoney = new BigDecimal(ratio).setScale(2, BigDecimal.ROUND_DOWN);
        StockInfo stockInfo = new StockInfo();
        stockInfo.setName(code.equals("USDCNH") ? "人民币汇率" : "美元指数");
        stockInfo.setNowPrice(priceMoney);
        stockInfo.setZde(increaseMoney);
        stockInfo.setZf(ratioMoney);
        return stockInfo;
    }

    public static StockInfo dealMarkPrice(List<StockInfo> stockInfos){
        List<StockInfo> list = stockInfos.stream().filter(stockInfo ->
                "sh000001".equals(stockInfo.getSearchCode()) || "sz399001".equals(stockInfo.getSearchCode())
        ).collect(Collectors.toList());
        BigDecimal marketPrice = list.stream().map(StockInfo::getMarketPrice).reduce(BigDecimal::add).get().divide(new BigDecimal("10000")).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal zde = list.stream().map(StockInfo::getZde).reduce(BigDecimal::add).get();
        BigDecimal zdf = list.stream().map(StockInfo::getZf).reduce(BigDecimal::add).get().divide(new BigDecimal("2")).setScale(2, BigDecimal.ROUND_DOWN);
        StockInfo marketPriceInfo = new StockInfo();
        marketPriceInfo.setName("两市市值");
        marketPriceInfo.setNowPrice(marketPrice);
        marketPriceInfo.setZde(zde);
        marketPriceInfo.setZf(zdf);
        return marketPriceInfo;
    }



    /**
     * 获取同花顺涨跌分布统计
     * @return
     */
    public static JSONObject getZdStatistics(){
        JSONObject result;
        String s = "";
        try {
            s = HttpUtil.get("https://x-quote.cls.cn/quote/index/home?app=CailianpressWeb&os=web&sv=8.4.6&sign=9f8797a1f4de66c2370f7a03990d2737");
            result = JSONObject.parseObject(s);
            result.put("code",200);
        }catch (Exception e){
            result = JSONObject.parseObject("{}");
            result.put("code",500);
            result.put("errmsg",e.getMessage());
            log.error("获取同花顺涨跌分布统计请求结果：{}", s);
            log.error("获取同花顺涨跌分布统计失败",e);
        }
        return result;
    }

    /**
     * 获取财联社成交额
     * @return
     */
    public static JSONObject getEmotion(){
        JSONObject result;
        String s = "";
        try {
            s = HttpUtil.get("https://x-quote.cls.cn/v2/quote/a/stock/emotion?app=CailianpressWeb&os=web&sv=8.4.6&sign=9f8797a1f4de66c2370f7a03990d2737");
            result = JSONObject.parseObject(s);
            result.put("code",200);
        }catch (Exception e){
            result = JSONObject.parseObject("{}");
            result.put("code",500);
            result.put("errmsg",e.getMessage());
            log.error("获取财联社成交额请求结果：{}", s);
            log.error("获取财联社成交额失败",e);
        }
        return result;
    }

    /**
     * 获取财联社涨跌幅榜单
     * @return
     */
    public static JSONObject getUpDownAnalysis(String type) {
        String url = "https://x-quote.cls.cn/quote/index/up_down_analysis?app=CailianpressWeb&os=web&rever=1&sv=8.4.6&type=" + type + "&way=last_px&sign=a6ab28604a6dbe891cdbd7764799eda1";
        try {
            String json = HttpUtil.get(url);
            return JSONObject.parseObject(json);
        } catch (Exception e) {
            JSONObject jsonObject = JSONObject.parseObject("{}");
            jsonObject.put("code",500);
            jsonObject.put("errmsg",e.getMessage());
            log.error("获取财联社涨跌幅榜单",e);
            return jsonObject;
        }
    }


}
